package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hjq.widget.ClearEditText;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.ParamMatchUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zwj on 2018/3/3.
 * 修改密码--个人
 */

public class PasswordForgetFragment extends BaseFragment implements View.OnClickListener{

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    private TextView topbar_textview_leftitle;
    private TextView topbar_textview_title;

    private ClearEditText name_edit;
    private ClearEditText idcard_edit;
    private ClearEditText bankcard_edit;
    private ClearEditText phone_edit;
    private ClearEditText code_edit;
    private TextView mSend;
    private SendSmsCodeCount mSendSmsCodeCount;
    private TextView next_text;
    //获取验证码返回的token
    private String tokenCode;

    //验证验证码返回的token
    private String mToken;

    private FormalUserInfo userInfo;

    //用户所属商户号
    private String oidpartner;

    public static PasswordForgetFragment newInstance(FormalUserInfo userInfo, String oid_partner) {
        Bundle args = new Bundle();
        PasswordForgetFragment fragment = new PasswordForgetFragment();
        args.putSerializable("userInfo",userInfo);
        args.putString("oid_partner", oid_partner);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
        oidpartner = getArguments().getString("oid_partner");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_password_forget, container, false);
        initView(view);
        return view;
    }

    private void initView(View view){
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_leftitle.setOnClickListener(this);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("找回密码");
        name_edit = (ClearEditText) view.findViewById(R.id.name_edit);
        idcard_edit = (ClearEditText) view.findViewById(R.id.idcard_edit);
        bankcard_edit = (ClearEditText) view.findViewById(R.id.bankcard_edit);
        phone_edit = (ClearEditText) view.findViewById(R.id.phone_edit);
        code_edit = (ClearEditText) view.findViewById(R.id.code_edit);
        mSend = (TextView) view.findViewById(R.id.send_text);
        mSend.setOnClickListener(this);
        next_text = (TextView) view.findViewById(R.id.next_text);
        next_text.setOnClickListener(this);
        mSendSmsCodeCount = new SendSmsCodeCount(60 * 1000, 100);
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.send_text:
                //发送
                check(phone_edit.getText().toString().trim());
                sendCode(oidpartner, "RSA",userInfo.getId() + "", bankcard_edit.getText().toString().trim(),
                        phone_edit.getText().toString().trim(), name_edit.getText().toString().trim(), idcard_edit.getText().toString().trim(),
                        SubmitCaseContent());
                break;
            case R.id.next_text:
                //下一步
                nextCode(oidpartner, "RSA",userInfo.getId() + "", tokenCode, code_edit.getText().toString().trim());
                break;
        }
    }

    /**
     * 风控参数
     * @return
     */
    private List<HashMap<String, String>> hashMapLists;
    public String SubmitCaseContent() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = "";
        if (hashMapLists == null)
            hashMapLists = new ArrayList<>();
        if (hashMapLists.size() > 0)
            hashMapLists.clear();

        HashMap<String, String> map = new HashMap<>();
        map.put("user_info_dt_register",df.format(new Date()));

        hashMapLists.add(map);

        if (hashMapLists == null) {
            return "";
        }
        StringBuilder mStringBuilder = new StringBuilder();

        for (int i = 0; i < hashMapLists.size(); i++) {
            String hashMapToJson = JsonUtils.hashMapToJson(hashMapLists.get(i));
            mStringBuilder.append(hashMapToJson).append(",");
        }
        if (mStringBuilder.length() > 0) {
            String substring = mStringBuilder.toString().substring(0, mStringBuilder.toString().lastIndexOf(","));
            content = substring;
        } else {

        }
        return content;
    }

    /**
     * 检测手机号
     * @param phone
     * @return
     */
    private boolean check(String phone) {
        if (TextUtils.isEmpty(phone)) {
            showShortToast("请填写手机号");
            return false;
        }

        if (!ParamMatchUtils.isPhoneAvailable(phone)) {
            showShortToast("请填写正确的手机号");
            return false;
        }
        return true;
    }

    /**
     * 绑定银行卡 授权 申请
     * @param oid_partner 用户所属商户号
     * @param sign_type 签名方式
     * @param user_id 用户唯一编号
     * @param card_no 银行卡号
     * @param bind_mob 绑定手机号码
     * @param acct_name 姓名
     * @param id_no 证件号
     * @param risk_item 风控参数
     */
    public void sendCode(String oid_partner, String sign_type, String user_id, String card_no, String bind_mob, String acct_name,
                         String id_no, String risk_item) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("oid_partner", oid_partner);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("card_no", card_no);
        mSendCodeHashMap.put("bind_mob", bind_mob);
        mSendCodeHashMap.put("acct_name", acct_name);
        mSendCodeHashMap.put("id_no", id_no);
        mSendCodeHashMap.put("risk_item", risk_item);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("oid_partner", oid_partner);
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("card_no", card_no);
        paramMaps.put("bind_mob", bind_mob);
        paramMaps.put("acct_name", acct_name);
        paramMaps.put("id_no", id_no);
        paramMaps.put("risk_item", risk_item);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.IS_WALLET_BANK, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    LogUtils.e("content_绑定银行卡授权申请", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        tokenCode = data.optString("token");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                _mActivity.onBackPressed();
                break;
        }
    }

    /**
     * 下一步
     *   绑定 银行卡 授权验证
     * @param oid_partner 用户所属商户号
     * @param sign_type 签名方式
     * @param user_id 用户唯一编号
     * @param token 验证token
     * @param verify_code 验证码
     */
    public void nextCode(String oid_partner, String sign_type, String user_id, String token, String verify_code) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("oid_partner", oid_partner);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("token", token);
        mSendCodeHashMap.put("verify_code", verify_code);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("oid_partner", oid_partner);
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("token", token);
        paramMaps.put("verify_code", verify_code);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.IS_BANK, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    LogUtils.e("content_ 绑定银行卡授权验证", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        mToken = data.optString("token");
                        startForResult(PasswordBackFragment.newInstance(userInfo, oidpartner, mToken), 1);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    class SendSmsCodeCount extends CountDownTimer {

        public SendSmsCodeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mSend.setEnabled(true);
            mSend.setTextColor(Color.parseColor("#79AB1C"));
            mSend.setGravity(Gravity.CENTER);
            mSend.setTextSize(14);
            mSend.setText("发送");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSend.setEnabled(false);
            if (millisUntilFinished / 1000 == 0) {
                onFinish();
            } else {
                mSend.setText(millisUntilFinished / 1000 + "");
                mSend.setTextColor(Color.parseColor("#B2B2B2"));
                mSend.setGravity(Gravity.CENTER);
                mSend.setTextSize(14);
            }
        }
    }
}
